package com.daka.exception;

import com.daka.enumerate.StatusCode;
import com.daka.tools.ServiceRuntimeException;
import com.daka.vo.response.BaseResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author Jay
 *         <p>
 *         Handle different kinds of exceptions being thrown from controllers
 *         <p>
 *         Transalate those exceptions into well formatted json string
 */
@ControllerAdvice
public class RestErrorHandler {

    @Resource
    private MessageSource messageSource;

    @Autowired
    public RestErrorHandler(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

//    @ExceptionHandler(HttpMessageNotReadableException.class)
//    @ResponseBody
//    public ResponseEntity<BaseResponseVo> processHttpMessageNotReadable() {
//        return new ResponseEntity<>(
//                new BaseResponseVo(-1, "服务器出问题了"), HttpStatus.OK);
//    }

    @ExceptionHandler(ServiceRuntimeException.class)
    @ResponseBody
    public BaseResponseVo processServiceRuntimeException(ServiceRuntimeException e) {
        return new BaseResponseVo(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseResponseVo processException(Exception e) {
        return new BaseResponseVo(StatusCode.SERVER_EXCEPTION.getCode(), e.getMessage());
    }


    private String message(String code) {
        return messageSource.getMessage(code, null, LocaleContextHolder.getLocale());
    }

    private String message(BindingResult result) {
        StringBuilder sb = new StringBuilder();
        List<FieldError> fieldErrors = result.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            sb.append(messageSource.getMessage(fieldError, LocaleContextHolder.getLocale()));
        }
        return sb.toString();
    }

}